<script lang="jsx" setup>
import { getCurrentInstance, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import Modal from '@/components/common/modal.vue';
import { get, post, put } from '@/service/api/api';
import underReview from '@/assets/imgs/examine-icon/under-review.png';
import unaudited from '@/assets/imgs/examine-icon/unaudited.png';
import audited from '@/assets/imgs/examine-icon/audited.png';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  },
  operateType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object,
    default: null
  }
});

const instance = getCurrentInstance();

console.log('props :>> ', props);
const emit = defineEmits(['addModalClose', 'addSuccess']);
const moduleNoList = ref([]);

const topFormList = ref([
  {
    type: 'tabs',
    span: 24,
    name: '基本项目'
  },
  {
    type: 'select',
    key: 'moduleNo',
    label: '生产型号',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    disabled: false,
    rule: {
      required: true,
      message: '请输入生产型号',
      trigger: 'change'
    },
    selectOptions: moduleNoList,
    search: true,
    disabled: props.operateType === 'look',
    change: e => {
      moduleNoChange(e);
    }
  },
  {
    type: 'datePicker',
    key: 'modifyTime',
    label: '时间',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showTime: true
  },

  {
    type: 'input',
    key: 'totalCheckNum',
    label: '总检查数',
    defaultValue: '0',
    span: 4,
    rule: {
      required: true,
      message: '请输入总检查数',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    change: () => {
      ngNumChange();
    },
    keypress: event => {
      if (event.key === '-') {
        event.preventDefault();
      }
    }
  },
  {
    type: 'input',
    key: 'ngNum',
    label: '不良数',
    span: 4,
    defaultValue: '0',
    disabled: true,
    change: () => {
      if (model.value.totalCheckNum != 0) {
        model.value.ngRate = `${((model.value.ngNum / model.value.totalCheckNum) * 100).toFixed(2)}%`;
      }
      model.value.okNum = model.value.totalCheckNum - model.value.ngNum;
      model.value.fqcArea = (this.fqcArea * model.value.totalCheckNum).toFixed(6);
    },
    keypress: event => {
      if (event.key === '-') {
        event.preventDefault();
      }
    }
  },
  {
    type: 'input',
    key: 'machineNo',
    label: '机台号',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    rule: {
      required: true,
      message: '请填写机台号',
      trigger: 'change'
    }
  },
  {
    type: 'select',
    key: 'region',
    label: '区域',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    disabled: false,
    rule: {
      required: true,
      message: '请选择区域',
      trigger: 'change'
    },
    selectOptions: [
      {
        label: '一期',
        value: '1'
      },
      {
        label: '二期',
        value: '2'
      }
    ]
  },
  {
    type: 'input',
    key: 'okNum',
    label: 'OK数',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    key: 'ngRate',
    label: '不良率',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    key: 'areaTrea',
    label: '表面处理',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    key: 'fqcArea',
    label: '面积(ft2)',
    span: 4,
    disabled: true
  },

  {
    type: 'input',
    key: 'operator',
    label: '检验员',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    key: 'foreman',
    label: '领班审核',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    key: 'examiner',
    label: '主管审核',
    span: 4,
    disabled: true
  },
  {
    type: 'radio',
    key: 'fqcCheckType',
    label: '检查类型',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        label: '一检',
        value: '一检'
      },
      {
        label: '二检',
        value: '二检'
      }
    ],
    rule: {
      required: true,
      message: '请选择检查类型',
      trigger: 'change'
    }
  },
  {
    type: 'radio',
    key: 'shiftType',
    label: '班别',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        label: '白班',
        value: '0'
      },
      {
        label: '夜班',
        value: '1'
      }
    ],
    rule: {
      required: true,
      message: '请选择班别',
      trigger: 'change'
    }
  },
  {
    type: 'input',
    key: 'dateCode',
    label: '周期',
    span: 4,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    rule: {
      required: true,
      message: '请填写周期',
      trigger: 'change'
    }
  },
  {
    type: 'textarea',
    key: 'remark',
    label: '备注',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    textareaRows: 1,
    span: 12
  }
]);

const modelVisible = ref(props.visible);
const modleAddLoading = ref(false);

const activeKey = '1';
const topFormRef = ref(null);
const fqcArea = ref(null);

const model = ref(getModel(topFormList.value));

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    obj[item.key] = item.defaultValue || null;
    if (props?.rowData) {
      obj[item.key] = props?.rowData?.[item.key];
    }
    if (item.tansfromDisabled) {
      item.disabled = item.tansfromDisabled(props.operateType);
    }
  });
  console.log('obj :>> ', obj);
  return obj;
}

function moduleNoChange(val) {
  get('/rcerp/agv/erp/findByModuleNo', {
    moduleNo: val
  }).then(({ data, error }) => {
    if (!error) {
      Object.keys(model.value).forEach(item => {
        model.value[item] = data[item];
      });
      fqcArea.value = data.fqcArea;
    }
  });
}

function getModuleNoList() {
  get('/rcerp/agv/erp/findModuleNo', {}).then(({ data, error }) => {
    if (!error) {
      moduleNoList.value = data.map(item => {
        return {
          value: item.moduleNo,
          label: item.moduleNo
        };
      });
    }
  });
}

function ngNumChange() {
  if (model.value.totalCheckNum != 0) {
    model.value.ngRate = `${((model.value.ngNum / model.value.totalCheckNum) * 100).toFixed(2)}%`;
  }

  model.value.okNum = model.value.totalCheckNum - model.value.ngNum;
  model.value.fqcArea = (model.value.fqcArea * model.value.totalCheckNum).toFixed(6);
}

const formBoxRef = ref(null);

const height = ref(169);

const tableData = ref([]);
function getTableData() {
  const url = props?.rowData ? `/qms/fqc/check1/listBad?id=${props.rowData.id}` : '/qms/fqc/check1/selectBadId';
  get(url, {}).then(({ data, error }) => {
    if (!error) {
      tableData.value = data;
    }
  });
}

function tableNumberChange(val) {
  let sum = 0;
  tableData.value.forEach(item => {
    item.list.forEach(row => {
      sum += row.number || 0; // 累加所有输入框的值
    });
  });
  model.value.ngNum = sum;

  if (val !== 0 && model.value.totalCheckNum != 0) {
    model.value.ngRate = `${((model.value.ngNum / model.value.totalCheckNum) * 100).toFixed(2)}%`;
    model.value.okNum = model.value.totalCheckNum - model.value.ngNum;
  }
}

async function handleOk(type) {
  const form = { ...topFormRef.value };
  let badDoList = [];
  tableData.value.forEach(item => {
    badDoList = [...badDoList, ...item.list];
  });
  await form.validateForm();

  const params = {
    ...model.value,
    badDoList
  };
  const msgObj = {
    add: '新增',
    edit: '修改'
  };
  let pro;
  let url = '/qms/fqc/check1/add';
  if (props.rowData) {
    params.id = props.rowData.id;
    url = '/qms/fqc/check1/update';
    pro = put(url, params);
  } else {
    pro = post(url, params);
  }
  modleAddLoading.value = true;

  pro
    .then(({ error }) => {
      if (!error) {
        message.success(`${msgObj[props.operateType]}成功`);
        const obj = { ...instance.parent.refs.commonSearchRef, ...instance.parent.refs.tableRef };
        obj.formReset();
        obj.tableSelectChange([]);
        handleClose();
      }
    })
    .finally(() => {
      modleAddLoading.value = false;
    });
}

function handleClose() {
  modelVisible.value = false;
  emit('addModalClose');
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
    if (val) {
      getModuleNoList();
      getTableData();
      topFormList.value.forEach(item => {
        if (item.tansfromDisabled) {
          item.disabled = item.tansfromDisabled(props.operateType);
        }
      });

      Object.keys(model.value).forEach(item => {
        if (props.rowData) {
          model.value[item] = props.rowData[item];
        } else {
          model.value[item] = model.value[item] ? model.value[item] : null;
        }
      });

      console.log('model :>> ', model.value);
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    :title="`${{ add: '新增', edit: '编辑', look: '查看' }[props.operateType]}FQC检验记录表`"
    height="98vh"
    width="98vw"
    :destroy-on-close="true"
    :centered="true"
    @close="handleClose"
  >
    <div class="single-FQC-add-form h-full">
      <div v-if="props.operateType !== 'add'" class="state">
        <template v-if="props.rowData.state === 0">
          <img :src="unaudited" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 2 || props.rowData.state === 4">
          <img :src="underReview" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 3">
          <img :src="audited" alt="examine-icon" />
        </template>
      </div>
      <div ref="formBoxRef" class="form w-full">
        <Form ref="topFormRef" v-model:model="model" :form-list="topFormList"></Form>
      </div>
      <div class="table-box" :style="{ height: `calc(100% - ${height + 4}px)` }">
        <div class="h-full w-full flex">
          <div
            v-for="(item, index) in tableData"
            :key="index"
            :style="{
              width: `${100 / tableData.length}%`
            }"
            :class="tableData.length - 1 === index ? 'my-last-table' : ''"
            class="h-full"
          >
            <div class="h-full w-full table">
              <div class="table-title w-full text-center font-bold">{{ item.name }}</div>
              <div class="table-header">
                <div class="tablde-col w-50% text-center font-bold">项目</div>
                <div class="tablde-col w-50% text-center font-bold">数量</div>
              </div>
              <div class="table-body">
                <div v-for="(row, rowIndex) in item.list" :key="rowIndex" class="table-row p2px">
                  <div class="table-col w-50% text-center">{{ row.badName }}</div>
                  <div class="table-col w-50% flex-center pl5px pr5px text-center">
                    <template v-if="props.operateType === 'look'">
                      {{ row.number }}
                    </template>
                    <template v-else>
                      <AInputNumber
                        v-model:value="row.number"
                        class="min-form-control w-full"
                        :min="0"
                        @change="tableNumberChange(row.number)"
                      ></AInputNumber>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="modal-footer">
        <AButton v-if="props.operateType == 'add'" type="primary" :loading="modleAddLoading" @click="handleOk('add')">
          保 存
        </AButton>
        <AButton v-if="props.operateType == 'edit'" type="primary" :loading="modleAddLoading" @click="handleOk('edit')">
          修 改
        </AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
</template>

<style lang="scss" scoped>
.single-FQC-add-form {
  border: 1px solid #ccc;
  padding: 0 30px;
  overflow: auto;
  position: relative;
  padding-top: 36px;
  padding-bottom: 15px;
  .state {
    position: absolute;
    top: 0;
    right: 100px;
    img {
      height: 80px;
    }
  }
  .table-box {
    .my-last-table {
      .table {
        border-right: 1px solid #000;
      }
    }
    .table {
      border: 1px solid #000;
      border-right: 0;

      .table-title {
        background-color: #ccc;
        height: 30px;
        line-height: 30px;
        font-size: 18px;
      }
      .table-header {
        display: flex;
        background: #e1e1e1;
      }
      .table-body {
        height: calc(100% - 52px);
        overflow: auto;
        .table-row {
          display: flex;
          border-bottom: 1px solid #ebeef5;
          font-family:
            ui-sans-serif,
            system-ui,
            -apple-system,
            BlinkMacSystemFont,
            'Segoe UI',
            Roboto,
            'Helvetica Neue',
            Arial,
            'Noto Sans',
            sans-serif,
            'Apple Color Emoji',
            'Segoe UI Emoji',
            'Segoe UI Symbol',
            'Noto Color Emoji';
        }
      }
    }
  }
}
</style>
